package chat;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * Created by 5406160@qq.com on LiBoWen 李博闻.
 *
 * @ClassName : Receive
 * @Author : 54061
 * @Date: 2022/2/25 18:48
 */
public class Receive implements Runnable {

    @Override
    public void run() {
        DatagramSocket receiveSocket = null;
        //创建接收端的Socket对象
        try {
            receiveSocket = new DatagramSocket(12345);
            boolean flag = true;
            while (flag){
                byte[] b  = new byte[1024];
                //创建封装数据的数据包对象
                DatagramPacket packet = new DatagramPacket(b,b.length);
                //接收发送方发送的数据
                receiveSocket.receive(packet);
                //获取发送方的ip地址
                InetAddress inetAddress = packet.getAddress();
                System.out.println("inetAddress.getHostAddress() = " + inetAddress.getHostAddress());
                //获取发送方发送的数据
                byte[] data = packet.getData();
                System.out.println("new String(b,0,packet.getLength()) = " + new String(b,0,packet.getLength()));

                
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            receiveSocket.close();
        }
    }
}
